<?php

namespace App\Http\Controllers\Admin\SystemMessage;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;

class SystemMessageController extends BaseController {

    /**
     * @api {post} /system-message 系统消息创建
     * @apiVersion 0.1.0
     * @apiName 系统消息-系统消息创建
     * @apiGroup 系统消息
     *
     *
     *
     * @apiParam {string} title                   标题
     * @apiParam {string} content                 内容
     * @apiParam {number} message_type            消息类型 1文字  2 图片
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'title' => 'required|string',
                'content' => 'required|string',
                'message_type' => 'required|numeric|integer|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $params = $request->input();

        $res = app('repo_message');
        $params['add_time'] = time();

        $rows = $res->addSysMessage($params);
        if (!$rows) {
            throw new BasicException(10001, "插入失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /system-message 系统消息删除
     * @apiVersion 0.1.0
     * @apiName 系统消息-系统消息删除
     * @apiGroup 系统消息
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode("," , $idsStr);

        $rows = app('repo_message')->delSysMessage($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /system-message 系统消息修改
     * @apiVersion 0.1.0
     * @apiName 系统消息-系统消息修改
     * @apiGroup 系统消息
     *
     *
     * @apiParam {number} id
     * @apiParam {string} title                   标题
     * @apiParam {string} content                 内容
     * @apiParam {number} message_type            消息类型 1文字  2 图片
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request) {
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'title' => 'required|string',
                'content' => 'required|string',
                'message_type' => 'required|numeric|integer|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $res = app('repo_message');

        $params = $request->input();
        $id = $params['id'];

        $res->saveSysMessage(["id" => $id], $params);

        return Response::sendData(true);
    }

    /**
     * @api {post} /system-message/send 发送消息
     * @apiVersion 0.1.0
     * @apiName 系统消息-发送消息
     * @apiGroup 系统消息
     *
     *
     * @apiParam {number} user_type               用户类型:1全部 2指定 3 男性 4 女性
     * @apiParam {string} user_codes                用户code字符串，逗号分隔
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function send(Request $request) {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'user_type' => 'required|numeric|integer|in:1,2,3,4,5,6,7',
                'user_codes' => 'filled|string',
            ]);
        if ($v->fails()) throw new BasicException(10001, $v->errors()->first());

        $res = app('repo_message');

        $params = $request->input();
        $id = $params['id'];

        if (isset($params['user_codes'])) {
            if ($params['user_type'] != 2 || empty($params['user_codes'])) {
                throw new BasicException(10001, '指定用户时必传用户编号！');
            }

            $userCodeArr = explode(",", $params['user_codes']);
            $userList = app("model_user_data")->whereIn("user_code", $userCodeArr)->select(["user_id"])->get();
            $userIdList = empty($userList) ? [] : array_column($userList->toArray(), "user_id");
            if (count($userCodeArr) != count($userIdList)) {
                throw new BasicException(10001, '用户编号不存在！');
            }
            $params['user_id_arr'] = $userIdList;
        }

        $params['admin_id'] = $request->admin_id ?? '';
        $rows = $res->sendSystemMessage($id, $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-message 系统消息列表
     * @apiVersion 0.1.0
     * @apiName 系统消息-系统消息列表
     * @apiGroup 系统消息
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "id(序号)": 21,
                "title(标题)": "111",
                "content(内容)": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f152ee1.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f160b88.jpg;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f16de56.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f180d4c.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f193101.jpg;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f1a0190.jpg;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f83817a.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f844cc4.jpg;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f853e5d.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f8687cf.jpg;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f8773d9.png;http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/admin_images/5f4775f885f2e.jpg",
                "message_type(消息类型 1文字  2 图片)": 2,
                "add_time(时间)": "2020-02-01"
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        }
     }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $list = app('repo_message')->getSysMessageQueryList($request->input());

        return Response::sendList($list);
    }

    /**
     * 日志记录列表
     * @param  Request  $request
     * @return string
     * @throws BasicException
     */
    public function listLog(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $list = app('repo_message')->getSysMessageLogQueryList($request->input());

        return Response::sendList($list);
    }
}
